<?php
/**
 * Created by PhpStorm.
 * User: HS032
 * Date: 2020/10/14
 * Time: 15:07
 */

namespace pay\modules\frontend\controllers;


use pay\libs\alipay\AliPayApi;
use pay\libs\CheckSign;
use pay\libs\Msg;
use pay\libs\Tools;
use pay\modules\frontend\models\Order;
use pay\modules\frontend\models\OrderDetails;
use pay\modules\frontend\models\RefundOrderLog;
use yii\base\Exception;
use yii\log\FileTarget;
use yii\web\Controller;
use Yii;

class AliPayController extends Controller
{

    public function beforeAction($action)
    {
        $origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
        $allow_origin = array(
            'http://10.9.87.108:8080',
            'http://view.horsevision.cn',
            'http://10.9.87.99:8080',
            'http://www.ysjg.co',
        );
        // P($origin);
        if (in_array($origin, $allow_origin)) {
            header('Access-Control-Allow-Origin:' . $origin);
            header('Access-Control-Allow-Methods:POST,GET');
            header('Access-Control-Allow-Credentials:true');
        }

        return true;
    }


    /**** 支付宝支付接口
     * @return false|string
     */
    public function actionTradePay()
    {
        if (\Yii::$app->request->isPost){
            $post = \Yii::$app->request->post();
            $CheckSignModel = new CheckSign();
            try{
                $paramsData = $CheckSignModel->checkSignAliPay($post); // 校验签名是否正确
                $orderStatus = $this->createOrder($paramsData); // 添加订单
                if ($orderStatus['code'] != 0){
                    throw new Exception($orderStatus['msg'],99);
                }
                $post = $orderStatus['msg'];
                $aliPayApi = new AliPayApi($post['channelMerId']);
                $method = $post['tradeType'].'Pay';
                $html = $aliPayApi->$method($post);
                return  Tools::showRes(0,'success',[
                    'data' => $html
                ]);
            }catch (Exception $e){
                return Tools::showRes($e->getCode(),$e->getMessage());
            }

        }
    }


    public function actionAliRefundOrder()
    {
        if (Yii::$app->request->isPost){
            $post = Yii::$app->request->post();
            $msgModel = new Msg();
            $orderModel = new Order();
            $CheckSignModel = new CheckSign();
            try{
                $postData = $CheckSignModel->checkSignAliRefund($post);
                $orderInfo = $orderModel->queryPayOrderInfo($postData['payNo']);
                if ($orderInfo['pay_status'] != 3){
                    throw new Exception('订单未支付',99);
                }
                $postData['paySerialId'] = $orderInfo['pay_order_sn'];
                $postData['refundFee'] = $postData['refundFee'] * 100;
                $refund_id = $this->addRefuncOrderLog($postData,$msgModel);
                    if ($refund_id){
                        $aliPayApi = new AliPayApi($post['channelMerId']);
                        $result = $aliPayApi->refund($postData);
                        $refundModel = RefundOrderLog::findOne($refund_id);
                        $refundModel->result_params = json_encode($result,JSON_UNESCAPED_UNICODE);
                        $refundModel->save(0);
                        if ($result->alipay_trade_refund_response->code == '10000' and $result->alipay_trade_refund_response->msg == 'Success'){
                            $this->UpdateOrder($orderInfo['oid'],$postData);
                            return Tools::showRes(0,'success');
                        }
                        throw new Exception('退款失败','10405');
                    }else{
                        throw new Exception('添加退款日志失败','99');
                    }
            }catch (Exception $e){
                return Tools::showRes($e->getCode(),$e->getMessage());
            }
        }

    }


    /*** 生成订单
     * @param $pay_order_sn
     * @param $post
     * @return array|false|string
     */
    private function createOrder($post)
    {
        $orderModel = new Order();
        $orderDetailsModel = new OrderDetails();
        $model = Order::find()->where('mar_order_sn = :msn and app_id = :aid',[':msn' => $post['payNo'],':aid' => $post['appId']])->andWhere(['pay_status' => 1])->asArray()->one();
        $msgModel = new Msg();
        $transaction = Yii::$app->db->beginTransaction();
        try{
            if (empty($model)){
                $pay_order_sn = Tools::createSn();  // 支付单号
                $post['pay_order_sn'] = $pay_order_sn;
                if (!$oid = $orderModel->addOrder($post)){
                    if ($orderModel->hasErrors()){
                        $this->recordAli('99','添加订单失败',json_encode($orderModel->getErrors()));
                        throw new Exception('添加订单失败');
                    }else{
                        throw new Exception('添加订单失败');
                    }
                }
                if (!$orderDetailsModel->addInfo($oid,$post)){
                    if ($orderDetailsModel->hasErrors()){
                        $this->recordAli('99','添加订单详情失败',json_encode($orderDetailsModel->getErrors()));
                        throw new Exception('添加订单失败');
                    }else{
                        throw new Exception('添加订单失败');
                    }
                }
            }else{
                $post['pay_order_sn'] = $model['pay_order_sn'];
            }
            $transaction->commit();
            return ['code' => 0,'msg' => $post];
        }catch (Exception $e){
            $transaction->rollBack();
            $msgModel->insertMsg('99',json_encode($post),$e->getMessage());
            return ['code' => 99,'msg' => $e->getMessage()];
        }
    }

    private function addRefuncOrderLog($postData,$msgModel)
    {
        $refuncOrderLogModel = new RefundOrderLog();
        if (!$refund_id = $refuncOrderLogModel->addLog($postData)){
            if ($refuncOrderLogModel->hasErrors()){
//                        $msgModel->insertMsg('refund-order','40056',json_encode($postData),json_encode($refuncOrderLogModel->getErrors()));
                $msgModel->insertMsg(40056,json_encode($refuncOrderLogModel->getErrors()),json_encode($postData));
                throw new Exception('添加退款失败',40056);
            }else{
                throw new Exception('添加退款失败',40056);
            }
        }
        return $refund_id;
    }


    public function UpdateOrder($oid,$data)
    {
        $transaction = Yii::$app->db->beginTransaction();
        try{
            $orderModels = Order::findOne($oid);
            $orderModels->pay_status = 5;
            $orderModels->ref_order_sn = $data['refundUserSerial'];
            $resInfo = $orderModels->save(0);
            $orderDetailsModel = new OrderDetails();
            $resDetail = $orderDetailsModel->addRefundInfo($oid,$data);
            if  ($resInfo and $resDetail){
                $transaction->commit();
                return true;
            }elseif($resInfo){
                throw new Exception('修改退款订单详情失败');
            }else{
                throw new Exception('修改退款订单失败');
            }
        }catch (Exception $e){
            $transaction->rollBack();
            $this->recordAli('99999','支付宝退款-'.$e->getMessage(),$oid);
            return false;
        }

    }


    protected function recordAli($code,$msg,$data)
    {
        $log = new FileTarget();
        $log->logFile = Yii::$app->getRuntimePath() . '/wxPay/pay_' . date('Ymd') . '.log';
        $log->messages[] = [
            "[url:{$_SERVER['REQUEST_URI']}],[data:{$code},{$msg},{$data}]",
            1,
            'application',
            time(),
        ];
        $log->export();
    }


}